<template>
  <view class="page-container">
    <!-- 帖子内容区域 -->
    <scroll-view
      class="content-scroll"
      scroll-y
      :style="{ height: scrollHeight + 'px' }"
    >
      <!-- 帖子头部信息 -->
      <view class="post-header">
        <view class="user-info">
          <u-avatar :src="postData.headImage" size="50"></u-avatar>
          <view class="user-meta">
            <text class="nickname">{{ postData.userName }}</text>
            <view class="meta-bottom">
              <text class="time">{{ postData.createTime }}</text>
              <text class="category">{{ postData.tags }}</text>
            </view>
          </view>
        </view>
        <text class="post-title">{{ postData.title }}</text>
      </view>

      <!-- 帖子内容 -->
      <view class="post-content">
        <rich-text :nodes="postData.content"></rich-text>

        <!-- 图片展示 -->
        <view class="image-list" v-if="postData.images">
          <u-image
            :src="postData.images"
            mode="widthFix"
            width="100%"
            @click="previewImage(index)"
          ></u-image>
        </view>
      </view>

      <!-- 帖子操作按钮 -->
      <view class="post-actions">
        <!-- 点赞 -->
        <view class="action-item" @click="handleLike">
          <u-icon
            :name="postData.isLiked ? 'thumb-up-fill' : 'thumb-up'"
            size="22"
            :color="postData.isLiked ? '#2979ff' : '#606266'"
          ></u-icon>
          <text>{{ postData.likeCount }}</text>
        </view>
        <!-- 收藏 -->
        <view class="action-item" @click="handleCollect">
          <u-icon
            :name="postData.isCollected ? 'star-fill' : 'star'"
            size="22"
            :color="postData.isCollected ? '#ff9900' : '#606266'"
          ></u-icon>
          <text>{{ postData.collectCount }}</text>
        </view>
        <view class="action-item" @click="handleEye">
          <u-icon name="eye" size="22"></u-icon>
          <text>{{ postData.viewCount }}</text>
        </view>
        <!-- <view class="action-item" @click="handleShare">
          <u-icon name="share" size="22" color="#606266"></u-icon>
          <text>分享</text>
        </view> -->
        <!-- <view class="action-item" @click="showMoreActions">
          <u-icon name="more-dot-fill" size="22" color="#606266"></u-icon>
          <text>更多</text>
        </view> -->
      </view>

      <!-- 评论区标题 -->
      <view class="comment-title">
        <text>评论</text>
        <text class="comment-count">{{ commentList.length }}</text>
      </view>

      <!-- 评论列表 -->
      <view class="comment-list">
        <view
          class="comment-item"
          v-for="(item, index) in commentList"
          :key="index"
        >
          <u-avatar :src="item.avatar" size="40"></u-avatar>
          <view class="comment-content">
            <view class="comment-header">
              <text class="comment-user">{{ item.nickname }}</text>
              <text class="comment-time">{{ item.createTime }}</text>
            </view>
            <text class="comment-text">{{ item.content }}</text>
            <view class="comment-actions">
              <view class="action-item" @click="handleCommentLike(index)">
                <u-icon
                  :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'"
                  size="20"
                  :color="item.isLiked ? '#2979ff' : '#606266'"
                ></u-icon>
                <text>{{ item.likeCount }}</text>
              </view>
              <view class="action-item" @click="showReplyInput(index)">
                <u-icon name="reply" size="20" color="#606266"></u-icon>
                <text>回复</text>
              </view>
            </view>
            <view v-if="replyInputs[index]" class="reply-input-container">
              <u-input
                v-model="replyInputs[index].content"
                placeholder="写回复..."
                border="none"
                shape="circle"
                :custom-style="{
                  backgroundColor: '#f5f5f5',
                  padding: '0 20rpx',
                }"
              ></u-input>
              <u-button
                type="primary"
                size="mini"
                shape="circle"
                @click="submitReply(index)"
                :disabled="!replyInputs[index].content.trim()"
                class="send-btn"
                >发送</u-button
              >
            </view>
            <view v-if="item.replies && item.replies.length">
              <view
                class="reply-item"
                v-for="(reply, replyIndex) in item.replies"
                :key="replyIndex"
              >
                <view class="reply-content">
                  <text class="reply-user">{{ reply.nickname }}</text>
                  <text> 回复 </text>
                  <text class="reply-to">{{ reply.replyTo }}</text>
                  <text>: {{ reply.content }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部安全距离 -->
      <view class="safe-area-bottom"></view>
    </scroll-view>

    <!-- 评论输入框 -->
    <view class="comment-input-container">
      <u-input
        v-model="commentContent"
        placeholder="写评论..."
        border="none"
        shape="circle"
        :custom-style="{ backgroundColor: '#f5f5f5', padding: '0 20rpx' }"
      ></u-input>
      <u-button
        type="primary"
        size="mini"
        shape="circle"
        @click="submitComment"
        :disabled="!commentContent.trim()"
        class="send-btn"
        >发送</u-button
      >
    </view>

    <!-- 更多操作菜单 -->
    <u-action-sheet
      :show="showActionSheet"
      :actions="actions"
      @close="showActionSheet = false"
      @select="actionSelect"
      title="更多操作"
      cancel-text="取消"
    ></u-action-sheet>
  </view>
</template>

<script>
import { getUserInfo_API } from "../../api/forum";
import {colloct_API, like_API} from "../../api/operation";

export default {
  data() {
    return {
      postId: 0, //帖子Id
      scrollHeight: 500, // 初始高度，将在onLoad中计算
      showActionSheet: false,
      commentContent: "",
      actions: [
        { name: "举报", color: "#f56c6c" },
        { name: "复制链接", color: "#606266" },
        { name: "刷新", color: "#606266" },
      ],
      postData: {},
      commentList: [
        {
          id: 1,
          avatar: "https://cdn.uviewui.com/uview/album/2.jpg",
          nickname: "前端小白",
          createTime: "2023-05-15 11:20",
          content: "这篇文章对我帮助很大，解决了我的问题！",
          likeCount: 0,
          isLiked: false,
          replies: [],
        },
        {
          id: 2,
          avatar: "https://cdn.uviewui.com/uview/album/3.jpg",
          nickname: "开发老鸟",
          createTime: "2023-05-15 12:45",
          content: "总结得很全面，特别是第3个问题我也遇到过",
          likeCount: 0,
          isLiked: false,
          replies: [],
        },
      ],
      replyInputs: {},
    };
  },
  onLoad(options) {
    // 获取帖子ID
    const postId = options.id || 1;
    this.postId = options.id || 1;
    // 这里应该调用API获取帖子详情数据
    this.loadPostData(postId);
    this.calculateScrollHeight();
  },
  onReady() {
    // 页面旋转时重新计算高度
    uni.onWindowResize(() => {
      this.calculateScrollHeight();
    });
  },
  methods: {
    // 计算可滚动区域高度
    calculateScrollHeight() {
      const systemInfo = uni.getSystemInfoSync();
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".comment-input-container")
        .boundingClientRect((data) => {
          const inputHeight = data.height;
          this.scrollHeight = systemInfo.windowHeight - inputHeight;
        })
        .exec();
    },

    // 加载帖子数据
    async loadPostData(postId) {
      // 这里应该调用API获取帖子详情
      console.log("加载帖子数据:", postId);
      const res = await getUserInfo_API({ postId });
      this.postData = res || {};
      console.log("res", res);
    },

    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.postData.images.map((item) => item.url),
      });
    },

    // 点赞
    async handleLike() {

      const res = await like_API({ postId: this.postId });
      this.postData.isLiked = !this.postData.isLiked;
      this.postData.likeCount += this.postData.isLiked ? 1 : -1;
      uni.showToast({ title: "操作成功", icon: "success" });
      // 这里应该调用API更新点赞状态
    },

    // 收藏
   async handleCollect() {
      const res = await colloct_API({ postId: this.postId });
      this.postData.isCollected = !this.postData.isCollected;
      this.postData.collectCount += this.postData.isCollected ? 1 : -1;
     uni.showToast({ title: "操作成功", icon: "success" });

      // 这里应该调用API更新收藏状态
    },

    // 操作选择
    actionSelect(index) {
      switch (index) {
        case 0: // 举报
          uni.navigateTo({
            url: "/pages/report/index?type=post&id=" + this.postData.id,
          });
          break;
        case 1: // 复制链接
          uni.setClipboardData({
            data: "https://yourdomain.com/post/" + this.postData.id,
            success: () => {
              uni.showToast({ title: "链接已复制", icon: "success" });
            },
          });
          break;
        case 2: // 刷新
          this.loadPostData(this.postData.id);
          break;
      }
    },

    // 提交评论
    submitComment() {
      if (!this.commentContent.trim()) return;

      const newComment = {
        id: Date.now(),
        avatar: "https://cdn.uviewui.com/uview/album/1.jpg", // 当前用户头像
        nickname: "当前用户", // 当前用户昵称
        createTime: "刚刚",
        content: this.commentContent,
        likeCount: 0,
        isLiked: false,
        replies: [],
      };

      this.commentList.unshift(newComment);
      this.commentContent = "";

      // 这里应该调用API提交评论
      uni.showToast({ title: "评论成功", icon: "success" });
    },

    // 评论点赞
    handleCommentLike(index) {
      this.commentList[index].isLiked = !this.commentList[index].isLiked;
      this.commentList[index].likeCount += this.commentList[index].isLiked
        ? 1
        : -1;
      // 这里应该调用API更新点赞状态
    },

    // 显示回复输入框
    showReplyInput(index) {
      this.replyInputs[index] = {
        content: "",
      };
    },

    // 提交回复
    submitReply(index) {
      if (!this.replyInputs[index].content.trim()) return;

      const newReply = {
        id: Date.now(),
        avatar: "https://cdn.uviewui.com/uview/album/1.jpg", // 当前用户头像
        nickname: "当前用户", // 当前用户昵称
        createTime: "刚刚",
        content: this.replyInputs[index].content,
        replyTo: this.commentList[index].nickname,
      };

      this.commentList[index].replies = this.commentList[index].replies || [];
      this.commentList[index].replies.push(newReply);
      this.replyInputs[index].content = "";
      delete this.replyInputs[index];

      // 这里应该调用API提交回复
      uni.showToast({ title: "回复成功", icon: "success" });
    },

    //
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  position: relative;
  height: 100vh;
  background-color: #f5f5f5;
}

.content-scroll {
  padding: 20rpx;
  box-sizing: border-box;
}

.post-header {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .user-meta {
      margin-left: 20rpx;

      .nickname {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .meta-bottom {
        display: flex;
        align-items: center;
        margin-top: 10rpx;

        .time {
          font-size: 24rpx;
          color: #999;
          margin-right: 20rpx;
        }

        .category {
          font-size: 24rpx;
          color: #2979ff;
          background-color: #ecf5ff;
          padding: 4rpx 12rpx;
          border-radius: 6rpx;
        }
      }
    }
  }

  .post-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    line-height: 1.5;
  }
}

.post-content {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  font-size: 32rpx;
  line-height: 1.8;
  color: #333;

  .image-list {
    margin-top: 30rpx;

    .u-image {
      margin-bottom: 20rpx;
      border-radius: 8rpx;
      overflow: hidden;
    }
  }
}

.post-actions {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 0;
  margin-bottom: 20rpx;

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 24rpx;
    color: #606266;

    text {
      margin-top: 10rpx;
    }
  }
}

.comment-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx 0;

  .comment-count {
    color: #999;
    margin-left: 10rpx;
  }
}

.comment-list {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;

  .comment-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .comment-content {
      flex: 1;
      margin-left: 20rpx;

      .comment-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10rpx;

        .comment-user {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }

        .comment-time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .comment-text {
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
      }

      .comment-actions {
        display: flex;
        margin-top: 10rpx;

        .action-item {
          display: flex;
          align-items: center;
          margin-right: 20rpx;
          font-size: 24rpx;
          color: #606266;

          text {
            margin-left: 5rpx;
          }
        }
      }

      .reply-input-container {
        display: flex;
        align-items: center;
        margin-top: 10rpx;

        .u-input {
          flex: 1;
          margin-right: 20rpx;
        }

        .send-btn {
          width: 120rpx;
        }
      }

      .reply-item {
        margin-top: 10rpx;
        padding-left: 20rpx;

        .reply-content {
          font-size: 26rpx;
          color: #666;
        }

        .reply-user {
          font-weight: bold;
        }

        .reply-to {
          font-weight: bold;
          color: #2979ff;
        }
      }
    }
  }
}

.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);

  .u-input {
    flex: 1;
    margin-right: 20rpx;
  }

  .send-btn {
    width: 120rpx;
  }
}

.safe-area-bottom {
  height: constant(safe-area-inset-bottom);
  height: env(safe-area-inset-bottom);
  width: 100%;
}
</style>
